<template>
  <d2-container>

    <template slot="header">
      <el-form :gutter="24" ref="search-box" :model="mainQuery"  label-position="left" :inline="true" size="mini">

        <el-col :span="8">
          <!-- 商户号 -->
          <el-form-item :label="$t('page-trade-refund.search-box.shopNo')" >
            <el-input placeholder="" v-model="mainQuery.mchNo" @keyup.enter.native="fetchMainData"  clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <!-- 交易流水号 -->
          <el-form-item :label="$t('page-trade-refund.search-box.tradeNo')" >
            <el-input placeholder="" v-model="mainQuery.tradeNo" @keyup.enter.native="fetchMainData"  clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">

          <!-- 处理状态 -->
          <el-form-item :label="$t('page-trade-refund.search-box.handleStatus')"  prop="type">
            <el-select v-model="mainQuery.handleStatus"  clearable>
              <el-option
                v-for="item in handleStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 申请时间 -->
        <el-form-item :label="$t('page-trade-refund.search-box.createTime')" >
          <el-date-picker
            v-model="dateTimeRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="onDateTimePickerChange" 
             :start-placeholder="$t('page.form.startDate')"
             :end-placeholder="$t('page.form.endTime')">
          </el-date-picker>
        </el-form-item>

      </el-form>

      <div class="search-btn-box">

        <div class="left">
       

        </div>
        <div class="right">
          <!-- 重置 -->
          <el-button size="mini" class="filter-item" icon="" type="default" @click="resetMainData" :loading="mainTable.loading" >{{ $t('page.search-box.reset') }}</el-button>
          <!-- 搜索 -->
          <el-button size="mini" class="filter-item" icon="el-icon-search" type="primary" @click="fetchMainData" :loading="mainTable.loading" >{{ $t('page.search-box.search') }}</el-button>
        </div>
      </div>
    </template>

    <!--主列表数据-->
    <d2-crud
      ref="d2Crud"
      selection-row
      :options="mainTable.options"
      :index-row="mainTable.indexRow"
      :columns="mainTable.columns"
      :data="mainTable.list"
      :loading="mainTable.loading"
      :rowHandle="mainTable.rowHandle"
      @current-change="onMainCurrentChange"
      @custom-emit-handle-order="handleOrderDetail"
      @selection-change="onMainSelectionChange"
    ></d2-crud>

    <template slot="footer">
      <el-pagination
        @size-change="handleMainSizeChange"
        @current-change="handleMainPageChange"
        :current-page="mainTable.pagination.currentPage"
        :page-sizes="mainTable.pagination.pageSizes"
        :page-size="mainTable.pagination.pageSize"
        :page-count="mainTable.pagination.pageCount"
        :total="mainTable.pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        :background="true"
        >
      </el-pagination>
    </template>

    <dialog-add ref="dialog-add" @dialog-close="fetchMainData"></dialog-add>

    <dialog-detail ref="dialog-detail" @dialog-close="fetchMainData"></dialog-detail>

    <dialog-upload ref="dialog-upload" @dialog-close="fetchMainData"></dialog-upload>

    <!-- <dialog-apply-list ref="dialog-apply-list"></dialog-apply-list> -->

  </d2-container>
</template>

<script>

import ApiMain from '@/api/trade.refund';
import DialogAdd from './dialog-add';
import DialogUpload from './dialog-upload';
import DialogDetail from '@/views/trade/detail/dialog-info';
import util from '@/libs/util.js';
import i18nTable from "@/mixins/i18n-table";
// import DialogApplyList from "./dialog-apply-list";

export default {
  mixins: [i18nTable
  ],
  components: {
    'dialog-add': DialogAdd,
    'dialog-detail': DialogDetail,
    'dialog-upload': DialogUpload,
    // DialogApplyList,
  },
  data () {
    return {

      mainQuery: {
        mchNo: '',
        terNo: '',
        tradeNo: '',
        level: '',
        handleStatus: '',
        startTime: '',
        endTime: ''
      },

      mainTable: {
        loading: false,
        options: {
          border             : true,
          stripe             : true,
          highlightCurrentRow: true,
          emptyText          : this.$t('page-announcement.d2-crud.empty-data'),
          size               : 'mini',
        },
        // indexRow: {
        //   title:this.$t('page.form.serialnumber'),
        //   width: "80",
        //   align:'center'
        // },
        indexRow: null,
        allowSelect: false,
        columns: [
          // 交易流水号
          {title: "单号", t: "page-trade-refund.d2-crud.column-tradeNo", key: 'tradeNo', align: 'center', minWidth: '180', showOverflowTooltip: true, fixed: true},
          // 商户号
          {title: "商户号", t: "page-trade-refund.d2-crud.column-mchNo", key: 'mchNo', align: 'center', minWidth: '180', showOverflowTooltip: true},
       
          // 交易金额
          {title:"交易金额", t: "page-trade-refund.d2-crud.column-mchTransAmount", key: 'mchTransAmount', align: 'right', minWidth: '140', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
            return row.mchTransCurrency + ' ' + (row.mchTransAmount / 100).toFixed(2);
          }},
          // 退款金额
          {title: "退款金额", t: "page-trade-refund.d2-crud.column-transAmount", key: 'transAmount', align: 'right', minWidth: '120', showOverflowTooltip: true, formatter(row, column, cellValue, index) {
            return row.transCurrency + ' ' + (row.transAmount / 100).toFixed(2);
          }},
          // 退款原因
          {title: "退款原因", t: "page-trade-refund.d2-crud.column-transReason", key: 'transReason', align: 'left', minWidth: '120', showOverflowTooltip: true},
          // 申请人
          // {title: this.$t('page-trade-refund.d2-crud.column-createBy'), key: 'createBy', align: 'center', minWidth: '120', showOverflowTooltip: true},
          // 申请时间
          {title: "申请时间", t: "page-trade-refund.d2-crud.column-createTime", key: 'createTime', align: 'center', minWidth: '180', showOverflowTooltip: true},
             // 处理状态
          {title: "处理状态", t: "page-trade-refund.d2-crud.column-handleStatus", key: 'strHandleStatus', align: 'center', minWidth: '120', showOverflowTooltip: true},
          // 处理人
          // {title: this.$t('page-trade-refund.d2-crud.column-reviewBy'), key: 'reviewBy', align: 'center', minWidth: '120', showOverflowTooltip: true},
          // 处理时间
          {title: "处理时间", t: "page-trade-refund.d2-crud.column-reviewTime", key: 'updateTime', align: 'center', minWidth: '180', showOverflowTooltip: true},
        ],
        rowHandle: {
          width: '120',
          align: 'center',
          fixed: 'right',
           t: "page.form.operation",
          columnHeader: this.$t('page.form.operation'),
          custom: [
            {
              // 订单详情
              text: "订单详情",
              t: "page-trade-refund.d2-crud.column-detail",
              type: 'default',
              size: 'mini',
              emit: 'custom-emit-handle-order'
            }
          ]
        },
        list: [],
        pagination: {
          currentPage: 1,
          pageSize   : 50,
          total      : 0,
          pageSizes  : [50, 100, 200]
        },
        selectionRow: [],
      },

      handleStatusOptions: [],
      dateTimeRange: []
    }
  },
  mounted () {
    this.fetchOptions();
    this.resetMainData();
  },
  beforeDestroy () {
  },
  methods: {

    // handleApplyList () {
    //   this.$refs["dialog-apply-list"].show();
    // },

    renderMainData (re) {
      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;
    },

    handleMainSizeChange (val) {
      this.mainTable.pagination.pageSize = val;
      this.fetchMainData()
    },
    handleMainPageChange (val) {
      this.mainTable.pagination.currentPage = val;
      this.fetchMainData()
    },

    buildMainQuery () {

      var query = {
        page  : this.mainTable.pagination.currentPage,
        limit : this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      return query;
    },

    resetMainData () {

      this.mainQuery = {
        mchNo: '',
        terNo: '',
        tradeNo: '',
        level: '',
        handleStatus: '',
        startTime: '',
        endTime: ''
      };

      this.fetchMainData();
    },

    async fetchMainData () {

      this.mainTable.loading = true;

      try {
        var re = await ApiMain.list(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) {}

      this.mainTable.loading = false;

    },

    async fetchOptions() {
      var re = await ApiMain.getStepOptions();
      this.handleStatusOptions = re;
    },

    onDateTimePickerChange() {
      this.mainQuery.startTime = this.dateTimeRange && this.dateTimeRange.length > 0 ? this.dateTimeRange[0] : ''
      this.mainQuery.endTime = this.dateTimeRange && this.dateTimeRange.length > 0 ? this.dateTimeRange[1] : ''
    },

    onMainCurrentChange (now, old) {
      this.mainTable.current = now;
    },

    onMainSelectionChange (now, old) {
      this.mainTable.selectionRow = now
    },

    onMainDoubleClick (now) {
      this.mainTable.current = now;
      this.handleSet();
    },

    handleAdd () {
      this.$refs['dialog-add'].show();
    },

    handleSet () {
      if (this.mainTable.current) {
        this.$refs['dialog-add'].show(this.mainTable.current.id);
      }
      else {
        // this.$message({message: '请选择一行数据', type: 'warning'});
      }

    },

    handleUpload () {
      this.$refs['dialog-upload'].show();
    },

    handleDownloadTemplate () {
      window.open(util.getDownloadTemplate('refund'), '_blank');
    },

    handleReview (handleStatus) {

      if (this.mainTable.selectionRow.length == 0) {
        this.$message({message: '请选择行', type: 'error'});
        return;
      }
      this.$confirm('确定操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doHandleReview(handleStatus)
      });

    },

    async doHandleReview (handleStatus) {

      let ids = []
      for (var i in this.mainTable.selectionRow) {
        if (this.mainTable.selectionRow[i].handleStatus == 1) {
          this.$message({message: '已审核的请勿重复操作', type: 'error'});
          return;
        }
        ids.push(this.mainTable.selectionRow[i].id);
      }
      let data = await ApiMain.handleStatus({ ids: ids.join(','), handleStatus: handleStatus });
      if (data == [] || data == '') {
        this.$message({message: '操作成功', type: 'success'});
      } else {
        this.$alert(data, '操作完成提示', {
          confirmButtonText: '确定'
        });
      }
      this.mainTable.selectionRow = [];
      this.fetchMainData();

    },

    handleOrderDetail ({index, row}) {
      this.$refs['dialog-detail'].show(row.orderId);
    },

  }
}
</script>

<style>

</style>
